package com.zhuss.food.processor;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.zhuss.bean.bo.food.order.wechat.CreateOrderBo;
import com.zhuss.bean.bo.food.order.wechat.CreateOrderProductBo;
import com.zhuss.bean.bo.food.order.wechat.CreateStirfryOrderBo;
import com.zhuss.bean.unit.core.user.UserBean;
import com.zhuss.bean.unit.food.Stirfry;
import com.zhuss.bean.vo.food.product.DetailProductVo;
import com.zhuss.common.AbstractProcessor;
import com.zhuss.common.Processor;
import com.zhuss.core.db.dao.ext.ScheduleDao;
import com.zhuss.core.processor.EnumConfig;
import com.zhuss.core.processor.ScheduleCreate;
import com.zhuss.core.processor.UserBindCheck;
import com.zhuss.db.entity.OpLog;
import com.zhuss.enums.Area;
import com.zhuss.enums.ConfigTypeEnum;
import com.zhuss.enums.EnumUtil;
import com.zhuss.enums.IsEnum;
import com.zhuss.enums.LogActionEnum;
import com.zhuss.enums.MoudleEnum;
import com.zhuss.enums.OrderStatus;
import com.zhuss.enums.ProductType;
import com.zhuss.exception.WpsException;
import com.zhuss.exception.ExceptionCode;
import com.zhuss.util.JsonUtil;


@Component("stirfryOrderCreate")
public class StirfryOrderCreate extends AbstractProcessor<Object, CreateStirfryOrderBo> implements Processor<Object, CreateStirfryOrderBo> {
	
	@Autowired
	@Qualifier("orderCreate")
	private Processor<Object, CreateOrderBo> orderCreate;
	
	@Autowired
	@Qualifier("productRead")
	private ProductRead productRead;
    
	
	@Autowired
	@Qualifier("enumConfig")
	private EnumConfig enumConfig;
	
	@Autowired
	private ProductCheck productCheck;
	
	@Autowired
	private ScheduleDao scheduleDao;
	
	@Autowired
	private UserBindCheck userBindCheck;
	
	@Autowired
	private OrderRead orderRead;
	
	@Override
	public void check(CreateStirfryOrderBo bo) throws WpsException {
		Long userId = bo.getConcurrentUserId();
		UserBean user = bo.getConcurrentUser();
		Integer isLimitArea = user.getIsLimitArea();
		Date expectFetchTimeStart = bo.getExpectFetchTimeStart();
		Date expectFetchTimeEnd = bo.getExpectFetchTimeEnd();
		if (!userBindCheck.process(userId)) {
			throw new WpsException(ExceptionCode.用户信息过期);
		}
		
		Integer area = bo.getArea();
		if (Area.东区.sameKey(area)) {
			List<Stirfry> list = bo.getStirfryList(); // 商品种类数
			Stirfry item = new Stirfry();
			if (list != null && !list.isEmpty()) {
				item = list.get(0);
			}
			
			Long buyCount = item.getCount();
			buyCount = buyCount == null ? 0 : buyCount;
			if (list.size() > 1 || buyCount > 1) {
				throw new WpsException(ExceptionCode.晚餐预定数量为1);
			}
			
			Long productId = item.getProductId();
			if (productId != null) {
				Integer alreadyBuyNum = orderRead.alreadyBuyNum(userId, productId);
				if (alreadyBuyNum > 0) {
					throw new WpsException(ExceptionCode.已预定过晚餐);
				}
			}
		}
		
		if (expectFetchTimeStart == null || expectFetchTimeEnd == null) {
			throw new WpsException(ExceptionCode.取餐时间不能为空);
		}
		
		
		Date end = enumConfig.getTime(ConfigTypeEnum.点炒截止点餐时间.value(), area);
		long now = System.currentTimeMillis();
		if (now < end.getTime()) {
			
		} else {
			throw new WpsException(ExceptionCode.超过点炒时间);
		}
		
		for (Stirfry s : bo.getStirfryList()) {
			Long productId = s.getProductId();
			DetailProductVo product = (DetailProductVo) productRead.detail(productId);
			
			if (!productCheck.checkCreateOrder(productId)) {
				throw new WpsException(ExceptionCode.当前商品已下架);
			}
			
			Integer productArea = product.getArea();
			if (!productArea.equals(area)) {
				throw new WpsException(ExceptionCode.下单区域商品不匹配);
			}
			
			Integer userArea = bo.getConcurrentUser().getArea();
			if (!userArea.equals(area) && IsEnum.是.sameKey(isLimitArea)) {
				throw new WpsException(ExceptionCode.请在所属区域下单);
			}
		}
		
		
		
	}

	@Override
	public Object process(CreateStirfryOrderBo bo) throws WpsException {
		String phone = bo.getPhone();
		Integer diningType = bo.getDiningType();
		String comment = bo.getComment();
		Long userId = bo.getConcurrentUserId();
		Date expectFetchTimeStart = bo.getExpectFetchTimeStart();
		Date expectFetchTimeEnd = bo.getExpectFetchTimeEnd();
		
		
		List<Stirfry> stirfryList = bo.getStirfryList();
		Integer productCount = stirfryList.size();  // 订购的商品的种类数
		Integer count = 0; // 订购的总件数
		Long amount = 0l; // 订购的总件数的总金额
		List<CreateOrderProductBo> createOrderProductBoList = new ArrayList<CreateOrderProductBo>();
		Integer area = bo.getArea();
		
		for (Stirfry s : stirfryList) {
			Integer eachProductCount =  s.getCount().intValue(); // 每个商品的订购数
			Long eachProductPrice = s.getPrice(); // 每个商品的价格
			Long eachProductAmount =  eachProductPrice * eachProductCount.longValue(); // 每个商品的总价
			count += eachProductCount;  // 每个商品的件数之和
			amount += eachProductAmount;  // 每个商品的金额之和
			
			Long productId = s.getProductId();
			DetailProductVo product = (DetailProductVo) productRead.detail(productId);
			
			CreateOrderProductBo c = new CreateOrderProductBo();
			c.setAmount(eachProductAmount);
			c.setCount(eachProductCount.longValue());
			c.setPrice(eachProductPrice);
			c.setProductName(product.getName());
			c.setProductNo(product.getProductNo());
			c.setProductId(product.getProductId());
			c.setStatus(OrderStatus.未接单.key());
			c.setConcurrentUserId(userId);
			createOrderProductBoList.add(c);
		}
		
		// 扣减点炒取餐时间区间库存 ，  返回受影响数量
		Integer influnce = scheduleDao.used(expectFetchTimeStart, 1, area);
		if (influnce.equals(0)) {
			throw new WpsException(ExceptionCode.当前取餐时间数量已满);
		}
		
		if (Area.中区.sameKey(area)) {
			List<Date> dateList = new ArrayList<Date>();
			try {
				dateList = ScheduleCreate.getStart2(new Date());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			expectFetchTimeStart = dateList.get(0);
			expectFetchTimeEnd = dateList.get(1);
		}
		
		CreateOrderBo orderBo = new CreateOrderBo();
		BeanUtils.copyProperties(bo, orderBo);
		orderBo.setAmount(amount);
		orderBo.setCount(count.longValue());
		orderBo.setProductCount(productCount.longValue());
		orderBo.setStatus(OrderStatus.未接单.key());
		orderBo.setType(ProductType.点炒服务.key());
		orderBo.setDiningType(diningType);
		orderBo.setComment(comment);
		orderBo.setConcurrentUserId(userId);
		orderBo.setCreateOrderProductBoList(createOrderProductBoList);
		orderBo.setArea(area);
		orderBo.setPhone(phone);
		orderBo.setExpectFetchTimeStart(expectFetchTimeStart);
		orderBo.setExpectFetchTimeEnd(expectFetchTimeEnd);
		orderCreate.process(orderBo);
		return null;
	}

	@Override
	public Object log(CreateStirfryOrderBo param) throws WpsException {
		OpLog record = new OpLog();
    	record.setMoudle(MoudleEnum.餐饮.key());
    	record.setAction(LogActionEnum.点炒服务订单创建.key());
    	record.setTargetId(param.getTargetId());
    	record.setTargetName(EnumUtil.containsKey(ProductType.class, ProductType.点炒服务.key()));
    	record.setContent("参数: " + JsonUtil.toJson(param));
    	record.setReason(param.getExceptionReason());
    	
    	record.setCreatorId(param.getConcurrentUserId());
    	record.setCreator(param.getConcurrentUserName());
    	record.setCreateTime(new Date());
    	log(record);
    	return null;
	}

}
